package org.ht.viewer;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.File;
import java.lang.reflect.Field;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;

import javax.swing.AbstractAction;
import javax.swing.AbstractButton;
import javax.swing.Action;
import javax.swing.ButtonGroup;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFormattedTextField;
import javax.swing.JOptionPane;
import javax.swing.JRadioButton;
import javax.swing.JTextArea;
import javax.swing.JTextField;

import org.azj.logHelper.LOG;
import org.ht.combotable.ComboTableFactory;
import org.ht.controller.ControlQueryDialog;
import org.ht.entity.Case;
import org.ht.entity.QueryEntity;
import org.ht.global.DbTableNames;
import org.ht.global.Global;
import org.swixml.SwingEngine;

/*
 * 新建病例对话框
 */
public class QueryDialog {

	// swixml 引擎
	SwingEngine swix = new SwingEngine(this);
	JDialog dialog;
	QueryDialog thisclass;
	private ControlQueryDialog controller = new ControlQueryDialog(this);

	// 关闭dialog后的结果
	private int colseResult = JOptionPane.DEFAULT_OPTION;

	public int getColseResult() {
		return colseResult;
	}

	public QueryDialog() {
		thisclass = this;

		String configs = System.getProperty("user.dir")
				+ "\\xml\\QueryDialog.xml";
		try {
			dialog = (JDialog) swix.render(new File(configs));
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 初始化
		init();
	}

	public void setVisible(boolean b) {
		dialog.setVisible(b);
	}

	// 控件
	JComboBox<String> Sex;
	JComboBox<String> HasInnercut;
	JComboBox<String> HasPusCultivation;
	JComboBox<String> DisScale;
	JComboBox<String> Incision;

	JTextField AgeInHospital1;
	JTextField AgeInHospital2;
	JTextField DisBreakOutDt1;
	JTextField DisBreakOutDt2;
	JTextField BodyTemprature1;
	JTextField BodyTemprature2;
	JTextField PreOpWBC1;
	JTextField PreOpWBC2;
	JTextField PreOpN1;
	JTextField PreOpN2;
	JTextField PreOpCRP1;
	JTextField PreOpCRP2;
	JTextField PreOpBloodSugar1;
	JTextField PreOpBloodSugar2;
	JTextField PostOpBodyTemp1;
	JTextField PostOpBodyTemp2;

	JCheckBox HealOpIgnore;
	JCheckBox HealOpDraggingWires;
	JCheckBox HealOpCathetering;
	JCheckBox HealOpSeton;

	// 特殊控件
	// JPanel DisBreakOutDt1_panel;
	// JPanel DisBreakOutDt2_panel;
	// JDatePicker DisBreakOutDt1;
	// JDatePicker DisBreakOutDt2;

	/**
	 * 初始化
	 */
	private void init() {

		Sex.setModel(new DefaultComboBoxModel<String>(new String[] { "", "男",
				"女" }));
		DisScale.setModel(new DefaultComboBoxModel<String>(new String[] { "",
				"1-2个象限", "2-3个象限", "3-4个象限" }));
		Incision.setModel(new DefaultComboBoxModel<String>(new String[] { "",
				"单纯小切口", "多点小切口", "全范围切开" }));
		HasInnercut.setModel(new DefaultComboBoxModel<String>(new String[] {
				"", "有", "无" }));
		HasPusCultivation.setModel(new DefaultComboBoxModel<String>(
				new String[] { "", "有", "无" }));
		HealOpIgnore.addItemListener(new ItemListener() {

			@Override
			public void itemStateChanged(ItemEvent e) {
				// TODO Auto-generated method stub
				Object obj = e.getItem();
				if (obj.equals(HealOpIgnore)) {
					if (HealOpIgnore.isSelected()) {
						HealOpCathetering.setSelected(false);
						HealOpCathetering.setEnabled(false);
						HealOpDraggingWires.setSelected(false);
						HealOpDraggingWires.setEnabled(false);
						HealOpSeton.setSelected(false);
						HealOpSeton.setEnabled(false);
					} else {
						HealOpCathetering.setEnabled(true);
						HealOpDraggingWires.setEnabled(true);
						HealOpSeton.setEnabled(true);
					}
				}
			}
		});
		HealOpIgnore.setSelected(true);

		// // 日期控件
		// DisBreakOutDt1 = new JDatePicker(JDatePicker.STYLE_CN_DATE1);
		// DisBreakOutDt1_panel.add(DisBreakOutDt1);
		// DisBreakOutDt2 = new JDatePicker(JDatePicker.STYLE_CN_DATE1);
		// DisBreakOutDt2_panel.add(DisBreakOutDt2);
	}

	/**
	 * 根据key获取控件内容转成string
	 */
	public String getText(String key) {
		String val = null;
		if (key == null) {
			assert key != null;
			return val;
		}
		try {
			Field field = this.getClass().getDeclaredField(key);
			Object obj = field.get(this);
			// 先处理特殊控件
			// switch (key) {
			// case "DisBreakOutDt1":
			// val = ((JDatePicker) obj).getSelectedDateString();
			// return val;
			// case "DisBreakOutDt2":
			// val = ((JDatePicker) obj).getSelectedDateString();
			// return val;
			// }

			if (obj instanceof JFormattedTextField) {
				val = ((JFormattedTextField) obj).getText();
			}
			if (obj instanceof ButtonGroup) {
				ButtonGroup group = (ButtonGroup) obj;
				Enumeration<AbstractButton> enu = group.getElements();
				while (enu.hasMoreElements()) {
					AbstractButton radioButton = enu.nextElement();
					if (radioButton.isSelected()) {
						val = radioButton.getText();
					}
				}
			}
			if (obj instanceof JCheckBox) {
				JCheckBox checkBox = (JCheckBox) obj;
				val = String.valueOf(checkBox.isSelected());

			}
			if (obj instanceof JRadioButton) {
				JRadioButton radioButton = (JRadioButton) obj;
				val = String.valueOf(radioButton.isSelected());
			}
			if (obj instanceof JTextField) {
				JTextField textField = (JTextField) obj;
				val = textField.getText();
			}
			if (obj instanceof JTextArea) {
				JTextArea textField = (JTextArea) obj;
				val = textField.getText();
			}
			if (obj instanceof JComboBox) {
				JComboBox jComboBox = (JComboBox) obj;
				val = jComboBox.getSelectedItem().toString();
			}
		} catch (NoSuchFieldException e) {
			System.out.println("界面内" + e.getMessage() + "未定义");
		} catch (SecurityException | IllegalArgumentException
				| IllegalAccessException e) {
			e.printStackTrace();
		}
		return val;
	}

	private QueryEntity getQueryEntity() {
		QueryEntity qe = new QueryEntity();
		qe.setAgeInHospital1(getText("AgeInHospital1"));
		qe.setAgeInHospital2(getText("AgeInHospital2"));
		qe.setDisBreakOutDt1(getText("DisBreakOutDt1"));
		qe.setDisBreakOutDt2(getText("DisBreakOutDt2"));
		qe.setBodyTemprature1(getText("BodyTemprature1"));
		qe.setBodyTemprature2(getText("BodyTemprature2"));
		qe.setPreOpWBC1(getText("PreOpWBC1"));
		qe.setPreOpWBC2(getText("PreOpWBC2"));
		qe.setPreOpN1(getText("PreOpN1"));
		qe.setPreOpN2(getText("PreOpN2"));
		qe.setPreOpCRP1(getText("PreOpCRP1"));
		qe.setPreOpCRP2(getText("PreOpCRP2"));
		qe.setPreOpBloodSugar1(getText("PreOpBloodSugar1"));
		qe.setPreOpBloodSugar2(getText("PreOpBloodSugar2"));
		qe.setPostOpBodyTemp1(getText("PostOpBodyTemp1"));
		qe.setPostOpBodyTemp2(getText("PostOpBodyTemp2"));

		qe.setDisScale(getText("DisScale"));
		qe.setIncision(getText("Incision"));
		qe.setSex(getText("Sex"));
		qe.setHasInnercut(getText("HasInnercut"));
		qe.setHasPusCultivation(getText("HasPusCultivation"));

		qe.setHealOpIgnore(Boolean
				.parseBoolean(getText("HealOpIgnore")));
		qe.setHealOpDraggingWires(Boolean
				.parseBoolean(getText("HealOpDraggingWires")));
		qe.setHealOpCathetering(Boolean
				.parseBoolean(getText("HealOpCathetering")));
		qe.setHealOpSeton(Boolean.parseBoolean(getText("HealOpSeton")));
		return qe;
	}

	private void fillDefault() {
		fillDefault("AgeInHospital");
		fillDefault("DisBreakOutDt");
		fillDefault("BodyTemprature");
		fillDefault("PreOpWBC");
		fillDefault("PreOpN");
		fillDefault("PreOpCRP");
		fillDefault("PreOpBloodSugar");
		fillDefault("PostOpBodyTemp");
	}

	private void fillDefault(String key) {
		try {
			Field field1 = this.getClass().getDeclaredField(key + "1");
			Object obj1 = field1.get(this);
			Field field2 = this.getClass().getDeclaredField(key + "2");
			Object obj2 = field2.get(this);
			if (obj1 instanceof JTextField) {
				JTextField textField1 = (JTextField) obj1;
				String val1 = textField1.getText();
				JTextField textField2 = (JTextField) obj2;
				String val2 = textField2.getText();
				if (val1.isEmpty() && !val2.isEmpty()) {
					String defaultval = controller.getDefault(key);
					textField1.setText(defaultval);
				} else if (!val1.isEmpty() && val2.isEmpty()) {
					String defaultval = controller.getDefault(key);
					textField2.setText(defaultval);
				}
			}
		} catch (NoSuchFieldException e) {
			System.out.println("界面内" + e.getMessage() + "未定义");
		} catch (SecurityException | IllegalArgumentException
				| IllegalAccessException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 点击确定按钮
	 */
	public Action okAction = new AbstractAction() {
		private static final long serialVersionUID = 1L;

		public void actionPerformed(ActionEvent e) {
			LOG.WriteLog("正在查询病例");
			int result = 0;
			try {
				// 如果只填了一个,就补上另一个的默认值
				fillDefault();
				QueryEntity qe = getQueryEntity();
				result = controller.check(qe);
				if (result == ControlQueryDialog.RESULT_OK) {
					// 查询MAP
					System.out.println(controller.getQemap());
					String where = query(controller.getQemap());
					try {
						List<String> pids = controller.query(where);
						// 删除旧数据
						Global.table.helper.clear();
						if (pids.size() == 0) {
							JOptionPane.showMessageDialog(dialog,
									"没有搜到任何符合要求的信息");
						} else {
							// 表格写入新数据
							List<Case> cases = Global.table.helper
									.getController().queryCases(pids);
							for (Case mycase : cases) {
								Global.table.helper
										.show(mycase,
												ComboTableFactory.instance
														.getVcolumn());
							}
						}
						// for (String pid : pids) {
						// Case newcase = Global.table.helper.getController()
						// .queryCase(pid);
						// // 显示在表中
						// Global.table.helper.show(newcase,
						// ComboTableFactory.instance.getVcolumn());
						// }

					} catch (Exception e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
				}
			} catch (Exception e1) {
				e1.printStackTrace();
			} finally {
				switch (result) {
				case ControlQueryDialog.RESULT_OK:
					// 注销窗口
					dialog.dispose();
					break;
				case ControlQueryDialog.RESULT_CHANGE:
					JOptionPane.showMessageDialog(null, "数值类型转换错误", "错误",
							JOptionPane.ERROR_MESSAGE);
					break;
				case ControlQueryDialog.RESULT_DB:
					JOptionPane.showMessageDialog(null, "数据库错误", "错误",
							JOptionPane.ERROR_MESSAGE);
					break;
				case ControlQueryDialog.RESULT_LIMIT:
					JOptionPane.showMessageDialog(null, "左边数值大于右边", "错误",
							JOptionPane.ERROR_MESSAGE);
					break;
				case ControlQueryDialog.RESULT_NULL:
					JOptionPane.showMessageDialog(null, "必须至少填一个值", "错误",
							JOptionPane.ERROR_MESSAGE);
					break;
				default:
					break;
				}
			}

		}
	};

	public Action cancelAction = new AbstractAction() {
		private static final long serialVersionUID = 1L;

		public void actionPerformed(ActionEvent e) {
			colseResult = JOptionPane.CANCEL_OPTION;
			dialog.dispose();
		}
	};

	private String query(Map<String, String> map) {
		String s = null;
		String table = null;
		StringBuffer where = new StringBuffer(" 1=1");
		fillquery(map, "AgeInHospital", DbTableNames.FullTblBasicInfo, where,
				"");
		fillquery(map, "DisBreakOutDt", DbTableNames.FullTblBeforeOp, where,
				"'");
		fillquery(map, "BodyTemprature", DbTableNames.FullTblBeforeOp, where,
				"");
		fillquery(map, "PreOpWBC", DbTableNames.FullTblBeforeOp, where, "");
		fillquery(map, "PreOpN", DbTableNames.FullTblBeforeOp, where, "");
		fillquery(map, "PreOpCRP", DbTableNames.FullTblBeforeOp, where, "");
		fillquery(map, "PreOpBloodSugar", DbTableNames.FullTblBeforeOp, where,
				"");
		fillquery(map, "PostOpBodyTemp", DbTableNames.FullTblPostOp, where, "");
		fillqueryForString(map, "Sex", DbTableNames.FullTblBasicInfo, where,
				"'");
		fillqueryForString(map, "DisScale", DbTableNames.FullTblBeforeOp,
				where, "'");
		fillqueryForString(map, "Incision", DbTableNames.FullTblMidOp, where,
				"'");
		fillqueryForString(map, "HasInnercut", DbTableNames.FullTblMidOp,
				where, "'");
		fillqueryForString(map, "HasPusCultivation", DbTableNames.FullTblMidOp,
				where, "'");
		
		fillqueryForString(map, "HealOpCathetering", DbTableNames.FullTblMidOp,
				where, "'");
		fillqueryForString(map, "HealOpDraggingWires", DbTableNames.FullTblMidOp,
				where, "'");
		fillqueryForString(map, "HealOpSeton", DbTableNames.FullTblMidOp,
				where, "'");
		System.out.println(where.toString());
		return where.toString();
	}

	private void fillquery(Map<String, String> map, String key, String table,
			StringBuffer where, String p) {
		String s = map.get(key);
		if (s != null) {
			where.append(" AND " + table + "." + key + " >= " + p
					+ s.split("@")[0] + p);
			where.append(" AND " + table + "." + key + " <= " + p
					+ s.split("@")[1] + p);
		}
	}

	private void fillqueryForString(Map<String, String> map, String key,
			String table, StringBuffer where, String p) {
		String s = map.get(key);
		if (s != null) {
			where.append(" AND " + table + "." + s.split("@")[0] + " = " + p
					+ s.split("@")[1] + p);
		}
	}
}
